import { Form, Input, Icon, Button, InputNumber, Col, Select, Row, message } from 'antd';
import React from 'react';
import { connect } from 'dva';
import BillUpload from './BillUpload';
import styles from './RYBill.less';

let id = 0;
@connect(({ fund, loading }) => ({
  fund,
  loading: loading.models.riskControlRule,
}))
class DynamicFieldSet extends React.Component {
  state = {
    newTags: [],
    inputVisible: false,
    inputValue: '',
  };

  componentDidMount() {
    this.props.onRef(this);
    const { record, isUpdate } = this.props;
    if (isUpdate && record) {
      for (let i = 0; i < record.length; i++) {
        this.add();
      }
    }
  }

  children = [];

  remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
    this.handleInputConfirm();
  };

  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  };

  handleSubmit = param => {
    const { record, isUpdate } = this.props;
    if (isUpdate) {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          const {
            keys,
            names,
            bill,
            exercisePrice,
            investmentMoney,
            ki,
            payPrice,
            redeemPeriod,
          } = values;
          console.log('Received values of form: ', values);
          console.log('Merged values:', keys.map(key => names[key]));
          console.log('Merged values:', keys.map(key => bill[key]));
          console.log('Merged values:', keys.map(key => ki[key]));
          const productDataDetailForms = [];
          // const id=record[0].id;
          for (let i = 0; i < keys.map(key => bill[key]).length; i++) {
            productDataDetailForms.push({
              exercisePrice: keys.map(key => exercisePrice[key])[i],
              investmentMoney: keys.map(key => investmentMoney[key])[i],
              ki: parseFloat(keys.map(key => ki[key])[i]),
              id: record[i].id,
              payPrice: keys.map(key => payPrice[key])[i],
              redeemPeriod: keys.map(key => redeemPeriod[key])[i],
            });
          }
          let dynamicFieldSetInputUpdate = false;
          for (let i = 0; i < record.length; i++) {
            if (
              record[i].exercisePrice !== productDataDetailForms[i].exercisePrice ||
              record[i].investmentMoney !== productDataDetailForms[i].investmentMoney ||
              parseFloat(record[i].ki) !== productDataDetailForms[i].ki ||
              record[i].payPrice !== productDataDetailForms[i].payPrice
            ) {
              dynamicFieldSetInputUpdate = true;
            }
          }
          if (!param.inputUpdate && !dynamicFieldSetInputUpdate) {
            message.success('信息未修改');
            return;
          }
          if (productDataDetailForms.length > 0) {
            const { dispatch } = this.props;
            dispatch({
              type: 'fund/BgUpdateBillData',
              payload: {
                billId: param.billId,
                id: param.id,
                finalDate: param.finalDate,
                frncoupon: param.frncoupon,
                iscnumber: param.iscnumber,
                p: param.p,
                price: param.price,
                redeemPrice: param.redeemPrice,
                transactionDate: param.transactionDate,
                x: param.x,
                updateBillDetailForms: productDataDetailForms,
              },

              callback: res => {
                if (res.code === 1) {
                  message.success('修改成功');
                  this.props.closeRecord();
                } else {
                  message.warning('修改失败');
                }
              },
            });
          } else {
            message.warning('请添加股票信息');
          }
        }
      });
    } else {
      console.log('param: ', param);
      this.props.form.validateFields((err, values) => {
        if (!err) {
          const {
            keys,
            names,
            bill,
            atMaturity,
            closePrice,
            exercisePrice,
            investmentMoney,
            ki,
            payPrice,
            redeemPeriod,
          } = values;
          console.log('Received values of form: ', values);
          console.log('Merged values:', keys.map(key => names[key]));
          console.log('Merged values:', keys.map(key => bill[key]));

          const productDataDetailForms = [];
          for (let i = 0; i < keys.map(key => bill[key]).length; i++) {
            productDataDetailForms.push({
              atMaturity: keys.map(key => atMaturity[key])[i],
              bill: keys.map(key => bill[key])[i],
              closePrice: keys.map(key => closePrice[key])[i],
              exercisePrice: keys.map(key => exercisePrice[key])[i],
              investmentMoney: keys.map(key => investmentMoney[key])[i],
              ki: keys.map(key => ki[key])[i],
              payPrice: keys.map(key => payPrice[key])[i],
              redeemPeriod: keys.map(key => redeemPeriod[key])[i],
            });
          }
          if (productDataDetailForms.length > 0) {
            const { dispatch } = this.props;
            dispatch({
              type: 'fund/BgAddBillData',
              payload: {
                badStockPrice: values.badStockPrice,
                badStock: values.badStock,
                billId: param.billId,
                billType: param.billType,
                currency: param.currency,
                d: param.d,
                finalDate: param.finalDate,
                frncoupon: param.frncoupon,
                iscnumber: param.iscnumber,
                p: param.p,
                price: param.price,
                productDataDetailForms,
                productID: param.productID,
                redeemPrice: param.redeemPrice,
                s: param.s,
                transactionDate: param.transactionDate,
                x: param.x,
              },
              callback: res => {
                if (res.code === 1) {
                  message.success('添加成功');
                  this.props.closeRecord();
                } else {
                  message.warning('添加失败');
                }
              },
            });
          } else {
            message.warning('请添加股票信息');
          }
        }
      });
    }
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    this.props.form.validateFields((err, values) => {
      const { keys, bill } = values;
      console.log('Received values of form: ', values);
      console.log('Merged values:', keys.map(key => bill[key]));
      this.children = [];
      for (let i = 0; i < keys.map(key => bill[key]).length; i++) {
        if (keys.map(key => bill[key])[i]) {
          this.children.push(
            <Option key={keys.map(key => bill[key])[i]}>{keys.map(key => bill[key])[i]}</Option>
          );
        }
      }
    });
  };

  render() {
    const { getFieldDecorator, getFieldValue, inputValue } = this.props.form;
    const { record, isUpdate } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };
    getFieldDecorator('keys', { initialValue: [] });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <div>
        <Form.Item
          {...(index === 0 ? formItemLayout : formItemLayout)}
          // label={index === 0 ? '请填写第'+id+'条信息' : ''}
          label={`请填写第${index + 1}条信息`}
          required={false}
          key={k}
        >
          {getFieldDecorator(`names[${k}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            // rules: [
            //   {
            //     required: true,
            //     whitespace: true,
            //     message: "Please input passenger's name or delete this field.",
            //   },
            // ],
          })
          // (<Input placeholder="passenger name" style={{ width: '60%', marginRight: 8 }} />)
          }
          {keys.length > 1 && !isUpdate ? (
            <Icon
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(k)}
            />
          ) : null}
        </Form.Item>

        <div>
          <Row>
            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="股票代码" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`bill[${k}]`, {
                    initialValue: isUpdate ? (index < record.length ? record[index].bill : '') : '',
                    rules: [
                      {
                        required: !isUpdate,
                        message: '请填写股票代码',
                      },
                    ],
                  })(
                    <Input
                      readOnly={isUpdate}
                      // onblur={this.handleChange}
                      value={inputValue}
                      onChange={this.handleInputChange}
                      onBlur={this.handleInputConfirm}
                      onPressEnter={this.handleInputConfirm}
                      style={{ width: '85%' }}
                      placeholder="股票代码"
                    />
                  )}
                </Form.Item>
              </Col>
            </Col>

            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="初始价" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`payPrice[${k}]`, {
                    initialValue: isUpdate
                      ? index < record.length
                        ? record[index].payPrice
                        : ''
                      : '',
                    rules: [
                      {
                        required: false,
                        message: '请填写初始价',
                      },
                    ],
                  })(<InputNumber style={{ width: '85%' }} placeholder="初始价" />)}
                </Form.Item>
              </Col>
            </Col>

            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="现货价" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`closePrice[${k}]`, {
                    rules: [
                      {
                        required: false,
                        message: '请填写上升参与率',
                      },
                    ],
                  })(
                    <InputNumber
                      readOnly={isUpdate}
                      style={{ width: '85%' }}
                      placeholder="请填写现货价"
                    />
                  )}
                </Form.Item>
              </Col>
            </Col>
          </Row>

          <Row>
            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="执行价" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`exercisePrice[${k}]`, {
                    initialValue: isUpdate
                      ? index < record.length
                        ? record[index].exercisePrice
                        : ''
                      : '',
                    rules: [
                      {
                        required: false,
                        message: '请填写执行价 ',
                      },
                    ],
                  })(<InputNumber style={{ width: '85%' }} placeholder="执行价" />)}
                </Form.Item>
              </Col>
            </Col>

            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="可赎回价格" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`redeemPeriod[${k}]`, {
                    initialValue: isUpdate
                      ? index < record.length
                        ? record[index].redeemablePrice
                        : ''
                      : '',
                    rules: [
                      {
                        required: false,
                        message: '请填写可赎回价格',
                      },
                    ],
                  })(
                    <InputNumber
                      // readOnly={isUpdate}
                      style={{ width: '85%' }}
                      placeholder="可赎回价格"
                    />
                  )}
                </Form.Item>
              </Col>
            </Col>

            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="金额比例" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`investmentMoney[${k}]`, {
                    initialValue: isUpdate
                      ? index < record.length
                        ? record[index].investmentMoney
                        : ''
                      : '',
                    rules: [
                      {
                        required: false,
                        message: '请填写金额比例',
                      },
                    ],
                  })(
                    <InputNumber
                      style={{ width: '85%' }}
                      placeholder="例如：0.10"
                      min={-1}
                      max={1}
                      step={0.1}
                    />
                  )}
                </Form.Item>
              </Col>
            </Col>
          </Row>
          <Row>
            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="ki" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`ki[${k}]`, {
                    initialValue: isUpdate ? (index < record.length ? record[index].ki : '') : '',
                    rules: [
                      {
                        required: false,
                        message: '请填写ki ',
                      },
                    ],
                  })(<InputNumber style={{ width: '85%' }} placeholder="ki" />)}
                </Form.Item>
              </Col>
            </Col>

            <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
              <Col span={24}>
                <Form.Item label="类型" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
                  {getFieldDecorator(`atMaturity[${k}]`, {
                    rules: [
                      {
                        message: '请选择股票类型',
                      },
                    ],
                  })(
                    isUpdate ? (
                      <Input readOnly style={{ width: '85%' }} />
                    ) : (
                      <Select style={{ width: '85%' }}>
                        <Option key="At maturity">At maturity</Option>
                        <Option key="Daily">Daily</Option>
                      </Select>
                    )
                  )}
                </Form.Item>
              </Col>
            </Col>
          </Row>
        </div>
      </div>
    ));

    return (
      <div>
        <Form>
          {formItems}
          {isUpdate ? (
            <div />
          ) : (
            <Form.Item {...formItemLayoutWithOutLabel}>
              <Button type="dashed" onClick={this.add} style={{ width: isUpdate ? '0%' : '60%' }}>
                <Icon type="plus" /> 添加股票信息
              </Button>
            </Form.Item>
          )}
        </Form>
        {isUpdate ? (
          <div />
        ) : (
          <div>
            <Row>
              <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
                <Col span={24}>
                  <Form.Item
                    label="最差表现挂钩股票"
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}
                  >
                    {getFieldDecorator(`badStock`, {
                      rules: [
                        {
                          required: !isUpdate,
                          message: '请选择最差表现挂钩股票',
                        },
                      ],
                    })(<Select style={{ width: '85%' }}>{this.children}</Select>)}
                  </Form.Item>
                </Col>
              </Col>

              <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
                <Col span={24}>
                  <Form.Item
                    label="最差表现挂钩股票接货值"
                    labelCol={{ span: 12 }}
                    wrapperCol={{ span: 12 }}
                  >
                    {getFieldDecorator(`badStockPrice`, {
                      rules: [
                        {
                          required: !isUpdate,
                          message: '请填写最差表现挂钩股票接货值',
                        },
                      ],
                    })(
                      <InputNumber
                        readOnly={isUpdate}
                        style={{ width: '100%' }}
                        placeholder="最差表现挂钩股票接货值"
                      />
                    )}
                  </Form.Item>
                </Col>
              </Col>
            </Row>
          </div>
        )}
      </div>
    );
  }
}

const WrappedDynamicFieldSet = Form.create({ name: 'dynamic_form_item' })(DynamicFieldSet);
export default WrappedDynamicFieldSet;
